const xss = require('xss')
let fs = require("fs");
let baseurl = "./png/";
const {
    exec
} = require("../db/mysql")

const RedisClient = require('../db/redis')

function getNowFormatDate(date) { //获取当前时间
    
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var strDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var getHours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var getMinutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var getSeconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
        " " + getHours + seperator2 + getMinutes +
        seperator2 + getSeconds;
    return currentdate;
}

const getList = (author, keyword,pagenunm) => {


    let sql = `select title,content,createtime,author,label,number,imgcode,id from blogs `

   // console.log(pagenunm)

     pagenunm =  parseInt(pagenunm)  ;
   
   pagenunm =  (pagenunm-1) * 10; 
   
    sql += `order by id desc LIMIT ${pagenunm} , 10 `
    

   let listData = {}; 

    return exec(sql).then((data) => {
       
        listData.data = data;

     return  exec('select count(*) from blogs;').then((data) =>{
       
        listData.number = data;
         return 1;
         
    }).then((data) => {

     return new Promise((resolve,reject) =>{

        resolve(listData)
    })
        })

    })
   

}

const getDetail = (id) => {

    console.log(id)

    const sql = `select title,content,createtime,author,label,number,html,imgcode from blogs where id = '${id}'`

    return exec(`select number from blogs where id = '${id}'`).then(res =>{

        console.log(res[0]);

        let data = JSON.stringify(res[0])

        let arr = data.split(':', 2)[1].replace('}', '')

        console.log(arr)
        data = parseInt(arr) + 1;
        
      return  exec(`update blogs set number = ${data} where id = ${id}`);     

    }).then(res => {
     
        return exec(sql)
        
 }).then(rows => {

        // console.log(rows);
        return rows[0];
    })   

    

}

const getDetails = (id) => {

    console.log(id)

    const sql = `select * from blogs where id = '${id}'`


    return exec(sql).then(rows => {

       //  console.log(rows);
        return rows[0];
    })

}




const newBlog = (blogData = {}) => {

    console.log(blogData);
    const xss = require('xss')
    const content = xss(blogData.content)


    const title = blogData.title
    const author = blogData.author
    let id;
    var date = new Date();
    const createTime = getNowFormatDate(date);

    const html = blogData.html;
    const label = blogData.label;
     const imgFile = blogData.imgFile
    const markdown = blogData.markdown

    
    var base64Data = imgFile.replace(/^data:image\/\w+;base64,/, "");

   
    var dataBuffer =  Buffer.from(base64Data, 'base64');
 

    let name = baseurl + Date.now() + ".png";

console.log(name);

    fs.writeFile(name, dataBuffer, function(err) {
        if(err){
         console.log(err);
        }else{
        console.log("ok")
        }
    });


   /* return exec("select max(id) from blogs;")
        .then((res) => {

            var data = JSON.stringify(res[0])

           

            let arr = data.split(':', 2)[1].replace('}', '')

           

            id = parseInt(arr) + 1;


            let promise = new Promise((resolve, reject) => {



                resolve(id)
            })

            return promise

        }) */

        // .then((id) => {

           name = name.replace(/./,""); 

            const sql = `insert into blogs (title,content,createtime,author,label,number,html,imgcode,markdown) values ('${title}','${content}','${createTime}','${author}','${label}',0,'${html}','${name}','${markdown}');`

          return  exec(sql).then(insertData => {

                 return{
                     id:insertData.insertId
                 } 
            })

        // })


}

const updataBlog = (id, blogData = {}) => {

    const title = xss(blogData.title)
    const content = xss(blogData.content)
     const {markdown,html,label,imgcode} = blogData;
    console.log(id);

    let name;

    console.log(imgcode)

    // 上传的图片base64不是空字符串的话进行处理,把base64 图片处理成png格式的图片并存起来
    if (imgcode !== "") {
        
        let base64Data = imgcode.replace(/^data:image\/\w+;base64,/, "");
        
        let dataBuffer = Buffer.from(base64Data, 'base64');
        
         name = baseurl + Date.now() + ".png";
        
        fs.writeFile(name, dataBuffer, function(err) {
            if(err){
             console.log(err);
            }else{
            console.log("ok")
            }
        });

        name = name.replace(/./,""); 
    }

    let sql = "";


    //如果base64 字符串不是空的话，把从存好的png图片的路径存到数据库里,否则不用改图片的路径和位置
    if (imgcode !== "") {
        sql  = `update blogs set title = '${title}',content = '${content}',markdown = '${markdown}' ,label = '${label}' , html = '${html}' ,imgcode = '${name}' where id = ${id} `
    } else {
        sql  = `update blogs set title = '${title}',content = '${content}',markdown = '${markdown}' ,label = '${label}' , html = '${html}'  where id = ${id} `
    }
     

    return exec(sql).then(updateData => {
       

        if (updateData.affectedRows > 0) {
            return true
        }

        return false
    })
}

const delBlog = (id, author) => {


    const sql = `delete from blogs where id = '${id}' and author = '${author}'`

    return exec(sql).then(delData => {
        console.log(delData)

        if (delData.affectedRows > 0) {
            return true
        }

        return false
    })
}

const gettime = () => {

    return new Promise((resolve, reject) => {
        

        RedisClient.get("time", (err, num) => {

            if (err) {
                reject(err);
            }

            // num 是 string 类型

            let obj = new Date(num - 0);

            let time = getNowFormatDate(obj);
            
            resolve(time)
        })

    })

}
const senddata = (name,content,email) =>{

    let sql = `insert into contact (name,email,content) values ("${name}","${email}","${content}");`

    return  exec(sql).then(insertData => {

        return{
            id:insertData.insertId
        } 
   })
}

const concern = (name,email,blogLink,notes) =>{

    let sql = `insert into concern (name,email,blogLink,notes) values ("${name}","${email}","${blogLink}","${notes}");`
    return  exec(sql).then(insertData => {

        return{
            id:insertData.insertId
        } 
   })

}

const getconcern = () =>{

    let sql = `select * from concern`
    return  exec(sql).then(insertData => {

        return insertData;
   })
}


const getsum = () => {
    
    let sql = `select id,title , createtime,label,content from blogs order by id desc; `

    let listData = {};
       

   return exec(sql).then((data) =>{

        listData.data = data;

     return  exec('select count(*) from blogs').then((data) =>{
       
        listData.number = data;
       
      return new Promise((resolve,reject) =>{
        resolve(listData)
    })

        })

    })

}

const getlabel = (name) =>{

    let sql = `select id,title , createtime, label from blogs where label = "${name}"  order by id desc;`

    return  exec(sql).then(insertData => {

        return insertData;
   })

}

const getcontactlist = () =>{
      
    let sql = `select * from contact;`

    return  exec(sql).then(insertData => {

        return insertData;
   })
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updataBlog,
    delBlog,
    gettime,
    senddata,
    concern,
    getconcern,
    getsum,
    getlabel,
    getcontactlist,
    getDetails
}